#include "AbsTable.h"
#include "SqlTool.h"
#include "DbConnectManager.h"


AbsTable::AbsTable(QString strTableName, QObject *parent)
    : QObject(parent),m_strTableName(strTableName)
{

}

bool AbsTable::dropTable()
{
    QString SQL = SqlTool::SQL_DROP_TABLE(m_strTableName);
    return this->execSql(SQL);
}

bool AbsTable::exisit()
{
    return dbConnection()->tables().contains(m_strTableName);
}

QSqlDatabase *AbsTable::dbConnection()
{
    //获取属于当前线程的数据库连接
    return DbConnectManager::getInstance()->getDbConnection();
}

QStringList AbsTable::columnNames()
{
    m_strListColumnNames.clear();

    QString strSql = QString("select * from %1 limit 1 offset 0").arg(m_strTableName);
    QSqlQuery query(*dbConnection());
    if(query.exec(strSql)){
        for(int i = 0; i < query.record().count(); ++i){
//            auto type = query.record().field(i).type();
            auto name = query.record().fieldName(i);
//            auto value = query.record().value(i).toString();
//            qDebug()<<QString("type:%1,name:%2,value:%3").arg(type).arg(name).arg(value);
            m_strListColumnNames.append(name);
        }

    }else{
        qWarning()<<"!!!!!"<<strSql<<query.lastError().text();
    }

    qInfo()<<"Columns:"<<m_strListColumnNames;
    return m_strListColumnNames;
}

bool AbsTable::execSql(QString strSql)
{
    QSqlQuery query(*dbConnection());

    if(!query.exec(strSql)){
        qWarning()<<"QSqlQuery erro,sql:"<<query.lastQuery()<<query.lastError().text();
        return false;
    }

    qInfo()<<"QSqlQuery ,sql:"<<query.lastQuery();

    return true;
}

bool AbsTable::exec(QSqlQuery &query)
{
    if(!query.exec()){
        qWarning()<<"QSqlQuery erro,sql:"<<query.lastQuery()<<query.lastError().text();
        return false;
    }

    qInfo()<<"QSqlQuery ,sql:"<<query.lastQuery();
    return true;
}

bool AbsTable::transaction()
{
    return dbConnection()->transaction();
}

bool AbsTable::commit()
{
    return dbConnection()->commit();
}
